package tech.deepmind.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 *
 * @Author: DeepMind
 * @Date: 2019年7月24日 上午9:39:07
 */
public class DBUtil {
	
	private static DBUtil instance = new DBUtil();
	private DBUtil() {}
	public static DBUtil getInstance() {
		if (instance == null) {
			instance = new DBUtil();
		}
		return instance;
	}

	private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/test";
	private static final String USER = "root";
	private static final String PASSWORD = "root";
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	
	static {
		try {
			Class.forName(DRIVER_CLASS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("驱动异常");
		}
	}
	private void getConnection() {
		try {
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("连接异常");
		}
	}
	/**
	 * 增删改查所有操作
	 * @return
	 */
	public void dopstmt(String sql,Object[] params) {
		 getConnection();
		 if(params == null) {
			 params = new Object[0];
		 }
		try {
			
			pstmt = conn.prepareStatement(sql);
			
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
			pstmt.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	/**
	 * 获取受影响的行数
	 * @return
	 * @throws SQLException
	 */
	public int getUpdateCount() throws SQLException {
		return this.pstmt.getUpdateCount();
	}
	/**
	 * 获取查询的结果集
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getResultSet() throws SQLException {
		return this.pstmt.getResultSet();
	}
	
	/**
	 * 释放资源
	 * @param rs
	 */
	public void closeAll(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (pstmt != null) {
				pstmt.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (conn != null || !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
